package com.wenshi;

import cn.hutool.core.io.resource.ResourceUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import com.wenshi.system.domain.ModbusMapping;
import com.wenshi.system.init.InitMappingMap;
import com.wenshi.system.service.ModbusMappingService;
import com.wenshi.web.netty.ModbusClient;
import com.wenshi.web.netty.MqttClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

import java.io.InputStream;
import java.util.List;
import java.util.stream.Collectors;

@Component
@Slf4j
public class Applicationrunner implements ApplicationRunner {

    @Autowired
    private ModbusClient modbusClient;
    @Autowired
    private MqttClient mqttClient;
    @Autowired
    private ModbusMappingService modbusMappingService;
    @Autowired
    private InitMappingMap initMappingMap;
    @Value("${file:path}")
    private String filePath;

    private final String iscsXlsxName = "mapping.xlsx";

    @Override
    public void run(ApplicationArguments args) throws Exception {
//        String value ="127.0.0.1";
//        modbusClient.setValue(value);
        Thread thread = new Thread(modbusClient);
        thread.start();
        String value ="127.0.0.1";

        mqttClient.setHost(value);
        mqttClient.setPort(1883);
        Thread thread2 = new Thread(mqttClient);
        thread2.start();
//        init();
        initMappingMap.init();
    }
    //初始化映射数据
    public void init(){
        //解析excel表数据信息  并存入数据库
        String os = System.getProperty("os.name");
        String resources = filePath + iscsXlsxName;
        InputStream stream = ResourceUtil.getStream(resources);
        ExcelReader readerSheet1= ExcelUtil.getReader(stream, 0);
        readerSheet1.setHeaderAlias(InitMappingMap.getHeaderAlias());
        List<ModbusMapping> writeEntities = readerSheet1.readAll(ModbusMapping.class);
        log.info("获取的数据长度{}",writeEntities.size());
        modbusMappingService.removeByIds(modbusMappingService.list().stream().map(ModbusMapping::getPlcAddress).collect(Collectors.toList()));
        boolean b = modbusMappingService.insertModbusMappingByList(writeEntities);
        if (b){
            log.info("初始化modbus点表数据成功");
        }
    }
}
